<template>
  <div class="article-page">
    <!-- 新增顶部标题 -->
    <h1 class="page-title">文章列表</h1>
    <!-- 文章发布表单，仅登录用户可见 -->
    <div v-if="isLogin" class="article-form-container">
      <form class="article-form">
        <div class="form-group">
          <label for="article-title">标题</label>
          <input
            type="text"
            id="article-title"
            v-model="title"
            placeholder="请输入文章标题"
          />
        </div>
        <div class="form-group">
          <label for="article-content">内容</label>
          <div id="editor-container">
            <Toolbar :editor="editorRef" :defaultConfig="toolbarConfig" mode="default" />
            <Editor
              v-model="valueHtml"
              :defaultConfig="editorConfig"
              mode="default"
              @onCreated="handleCreated"
            />
          </div>
        </div>
        <button type="button" class="submit-button" @click="addArticle">提交</button>
      </form>
    </div>
    <hr class="divider" />
    <!-- 文章列表 -->
    <div class="article-list">
      <div v-for="article in articles" :key="article.id" class="article-item">
        <router-link :to="{ name: 'articledetail', query: { id: article.id } }" class="article-link">
          <h2 class="article-title">{{ article.title }}</h2>
        </router-link>
        <p class="article-meta">
          作者: {{ article.authorName }} | 时间: {{ article.addedTime }}
        </p>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onBeforeUnmount, shallowRef } from 'vue';
import '@wangeditor/editor/dist/css/style.css';
import { Editor, Toolbar } from '@wangeditor/editor-for-vue';
import { getList, add } from '../utils/request';
import { useUserStore } from '../stores/user';
import { ElMessageBox } from 'element-plus';

const userStore = useUserStore();
const isLogin = ref(userStore.isAuthenticated);
const editorRef = shallowRef();
// 工具栏配置
const toolbarConfig = reactive({
  excludeKeys: [
    'blockquote',
    'headerSelect',
    'color',
    'bgColor',
    'fontSize',
    'fontFamily',
    'lineHeight',
    '|',
    'group-more-style',
    'group-indent',
    'emotion',
    'bulletedList',
    'numberedList',
    'divider',
    'todo',
  ],
});

const title = ref('');
const user = ref(userStore.getUser);
const addArticle = async () => {
  if (user.value && user.value.id) {
    if (!title.value || !valueHtml.value) {
      ElMessageBox.alert('标题和内容不能为空', '提示');
      return;
    }
    const newArticle = {
      title: title.value,
      body: valueHtml.value,
      userid: user.value.id,
    };
    const r = await add(newArticle);
    if (r) {
      // 手动将新文章添加到本地文章列表中
      articles.value.push({
        ...newArticle,
        id: Date.now(), // 这里简单用时间戳模拟文章ID，实际应从服务器返回
        addedTime: new Date().toLocaleString(), // 模拟文章添加时间
        authorName: user.value.name // 假设用户对象中有name属性
      });
      title.value = '';
      valueHtml.value = '';
      // 为了保证数据一致性，还是可以在后台重新获取列表
      getList().then(data => {
        articles.value = data;
      });
    }
  } else {
    ElMessageBox.alert('请先登录', '提示');
  }
};
// 内容 HTML
const valueHtml = ref('');

const editorConfig = {
  placeholder: '请输入内容...',
  MENU_CONF: {
    uploadImage: {
      server: '/api/demo/image',
      maxFileSize: 10 * 1024 * 1024,
      onFailed(file, res) {
        console.log(`${file.name} 上传图片失败`, res);
      },
      onError(file, err, res) {
        const showSize = getShortSizeStr(this.maxFileSize);
        ElMessageBox.alert('上传图片失败,最大不能超过' + showSize);
        console.log(`${file.name} 上传图片出错`, err, res);
      },
    },
    uploadVideo: {
      server: '/api/demo/video',
      maxFileSize: 50 * 1024 * 1024,
      onFailed(file, res) {
        console.log(`${file.name} 上传视频失败`, res);
      },
      onError(file, err, res) {
        const showSize = getShortSizeStr(this.maxFileSize);
        ElMessageBox.alert('上传视频失败,最大不能超过' + showSize);
        console.log(`${file.name} 上传视频出错`, err, res);
      },
    },
  },
};

function getShortSizeStr(realSize: number, fixedLength = 0) {
  let showSize = '';
  if (realSize < 1024 * 1024) {
    showSize = (realSize / 1024).toFixed(fixedLength) + 'KB';
  } else {
    showSize = (realSize / (1024 * 1024)).toFixed(fixedLength) + 'MB';
  }
  return showSize;
}

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});

const handleCreated = (editor: any) => {
  editorRef.value = editor;
};

const articles = ref<any[]>([]);
const isLoading = ref(true);

onMounted(async () => {
  try {
    const data = await getList(1);
    articles.value = data;
  } catch (error) {
    console.error('获取文章列表失败:', error);
  } finally {
    isLoading.value = false;
  }
});
</script>

<style scoped>
.article-page {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.page-title {
  font-size: 32px;
  text-align: center;
  margin-bottom: 20px;
}

.article-form-container {
  background-color: #f9f9f9;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
}

.article-form {
  display: flex;
  flex-direction: column;
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  font-weight: bold;
  margin-bottom: 5px;
}

.form-group input {
  width: 100%;
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 4px;
}

#editor-container {
  border: 1px solid #ccc;
  border-radius: 4px;
}

.submit-button {
  background-color: #28a745;
  color: white;
  padding: 10px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.submit-button:hover {
  background-color: #218838;
}

.divider {
  border: none;
  border-top: 1px solid #e0e0e0;
  margin: 20px 0;
}

.article-list {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 20px;
}

.article-item {
  background-color: #fff;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  padding: 20px;
  transition: box-shadow 0.3s;
}

.article-item:hover {
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}

.article-link {
  text-decoration: none;
  color: #333;
}

.article-title {
  font-size: 20px;
  margin-bottom: 10px;
}

.article-meta {
  font-size: 14px;
  color: #666;
}
</style>